import {getProductInfo,getProductById,getTProductById,getProductComment,reqPro,reqTimesss,reqClearljt,proname} from '../../api/scenicdetails'
import {reqSelstatus} from '../../api/order'
import {reqGetInventory} from '../../api/inventory'

// pages/scenicdetails/scenicdetails.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollIntoId: '',
    product:{},//产品
    productInfo:[{
      chinesestr:'',
      englishstr:''
    }],//产品类型集合
    commentList:[    {plimg:[]}],
    chineseText: "",//中文字符串
    englishText: "",//英文字符串
    isAcvite:false,
    date: '',
    showCalendar: false,
    dateList: [], // 存储日期数据
    choose:'',
    num:'1',
    isFixed: false,
    show:true,
    value: 3,
    comment:{name:'小小萌'},
    back:false,
    scrollTop:0,
    showxq: false,
    yd:false,
    seleweekday:'',
    titleList:[1,2,3,4],
    sectionTops:[],  //存每个区块top的数组
    maxDate: new Date().getTime() + 14 * 24 * 60 * 60 * 1000, // 15天后
    address:true,
    a:'',
    ticket:{'name':'','jiabeforetext':'','jiaaftertext':'','num':1,'playtime':'', 'total': 0,'price':'','id':'','inventory':''},
    jiabeforetext:'',
    jiaaftertext:'',
    showticke2:false,
     calendarSource: null,
     timeSlots: [],       // 存储所有时间段选项
     selectedTimeSlot: '', // 当前选中的时间段
     ordid:0,
     timeabc:'',
    isdisable:false,
    token:'',
    user:{},
    ljt:'',
    yupiao:0, //余票
    playtime:'',
    xq:[],
    ids:''
  },
  //算两个时间之间的差值
  calculateTimeDiff(startTime, nowTime, endTime) {
    // 补充默认日期，构造Date对象
    const startDate = new Date(startTime)
    const nowDate = new Date(nowTime);
    const endDate = new Date(endTime);
    console.log(startDate+"========="+nowDate+"============"+endDate+"+======="+endTime)
    //直接时间戳不等式判断
    if(nowDate.getTime()<endDate.getTime()){
      console.log("现在可以买票！")
      return true
    }else{
      console.log("现在不可以买票！")
      return false
    }
  },
  //获得当前时间方法
  getNowTime(){
    //输出当前时间
    const now = new Date();
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const formattedDate = `${hours}:${minutes}:${seconds}`;
    console.log(formattedDate); // 输出格式如 "10:36:11"
    return formattedDate
  },
  //获得当前年份方法
  getNowYear(){
    const now = new Date();
    //计算当前年份
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始需+1
    const day = String(now.getDate()).padStart(2, '0');
    const date = `${year}-${month}-${day}`
    return date
  },
  formatDate2(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    // 月份从 0 开始，所以要 +1
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); 
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},
  // 将ISO时间或Date对象转为HH:mm格式
formatTimeToHHMM(time) {
  if (!time) return '';
  // 如果是ISO格式字符串
  if (typeof time === 'string') {
    const date = new Date(time);
    const hours = date.getHours().toString().padStart(2, '0');
    const mins = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${mins}`;
  }
  
  return time; // 如果已经是HH:mm格式则直接返回
},
async yd(e){
  //这是小萌写的判断
  console.log(e.currentTarget.dataset.playtime)
  if(this.data.token==null || this.data.token==''){
    wx.showToast({
      title: '登录即可预订',
      icon:'error'
    })
    return;

  }else{
  
  if(e.currentTarget.dataset.playtime==null){
    this.setData({ yd: true });
  }else{
    //获得当前时间
    const now=this.getNowTime()
    let year2 = ''
    const now111 = new Date();
    //当前年份
    const year111 = now111.getFullYear();
    const choose=year111+'-'+this.data.choose.replace(".","-")
    const d1=new Date(choose)
    let shaa=true
    const year=this.getNowYear()
    const d2=new Date(year)
    if(d1.getTime()<=d2.getTime()){//说明购买的是今天的票，进行时间判断
      let starTime=new Date(e.currentTarget.dataset.playtime)
      let endTime=new Date(e.currentTarget.dataset.endplaytime)
      console.log(this.formatDate2(starTime))
      console.log(this.formatDate2(endTime))
      starTime=this.formatDate2(starTime).substring(11)
      endTime=this.formatDate2(endTime).substring(11)
      if(endTime.substring(0,2)!="00"){
        endTime=year+" "+endTime
        console.log(endTime)
      }else{
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1); // 自动处理跨月/跨年
        console.log(tomorrow.toISOString().split('T')[0]); // 输出YYYY-MM-DD格式
        year2=tomorrow.toISOString().split('T')[0]
        endTime=year2+" 00"+endTime.substring(2)
      }
      console.log(endTime)
      shaa=this.calculateTimeDiff(year+" "+starTime,year+" "+now,endTime)
      console.log(shaa)
    }else{//说明是明天的票。直接能买了老铁那还算啥了
      shaa=true
    }
    if(shaa==true){
      this.setData({ yd: true });
    }else{
      wx.showToast({
        title: '购票未开放',
        icon: 'error'
      })
    }
  }
  const aaa=await reqPro(e.currentTarget.dataset.a);
  let minpeoplenum=1
  if(aaa.data.pro.productType){//套餐
    const d=await getTProductById(aaa.data.pro.productId)
    minpeoplenum=d.data.product.minpeople
  }else{//单品
    const d=await getProductById(aaa.data.pro.productId)
    minpeoplenum=d.data.product.minpeople
  }
  console.log(aaa)
  const bbb=this.splitText(aaa.data.pro.pdName);
  // 格式化时间
  const playtime = this.formatTimeToHHMM(aaa.data.pro.playtime);
  const endplaytime = this.formatTimeToHHMM(aaa.data.pro.endplaytime);
  
  // 生成时间段
  let timeSlots = [`${playtime}-${endplaytime}`];

  if (!this.isAfternoon(playtime)) {
    timeSlots = [
      `${playtime}-12:00`,
      `12:00-${endplaytime}`
    ];
  }
  // 获取当前时间
  const now = new Date();
  const currentHour = now.getHours();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
const date = now.getDate().toString().padStart(2, '0');
const nowday = `${month}.${date}`; 
  let isdisable=false
  // 如果是下午（12点以后），禁用上午时间段

  let targetSlot=''
  if(nowday===this.data.choose){
  if(currentHour>=12 && (!this.isAfternoon(playtime))){
    targetSlot =  timeSlots[1] 
    isdisable=true
  }else{
    targetSlot= timeSlots[0]
  }
}else{
  targetSlot = timeSlots[0];
  isdisable = false;
}
  const ticketNum = this.data.ticket.num;
  const price = aaa.data.pro.pdPrice;
  const total = Math.floor(ticketNum * price);

    this.setData({
'playtime':playtime,
      isdisable,
      'ticket.inventory':aaa.data.pro.inventory,
      'ticket.id':aaa.data.pro.productDetailId,
      'ticket.productType':aaa.data.pro.productType,
      'ticket.minpeople':minpeoplenum,
      'ticket.productId':aaa.data.pro.productId,
      'ticket.num': 1,
      'ticket.rule':aaa.data.pro.rule,
      'ticket.price':aaa.data.pro.pdPrice,
      'ticket.name':this.data.chineseText,
      'ticket.jiaaftertext':this.data.jiaaftertext,
      'ticket.jiabeforetext':this.data.jiabeforetext,
      showticke2:this.data.chineseText.includes('+'),
      timeSlots, // 存储所有时间段
      selectedTimeSlot: targetSlot,
      'ticket.playtime': targetSlot,
      'ticket.total':total
      },() => {
        // setData完成后的回调，确保数据已更新
        console.log('数据更新完成，当前总价:', this.data.ticket);
      })
    }
  },

  // 辅助函数：判断时间是否是下午
isAfternoon(timeStr) {
  const hour = parseInt(timeStr.split(':')[0]);
  return hour >= 12; // 12点及以后算下午
},

  onCloseyd(){
    this.setData({ yd: false,'ticket.num': 1 });
  },
 async showPopup(e) {
     // 异步获取详情数据
     if(e.currentTarget.dataset.type==1){
     let res = await proname(e.currentTarget.dataset.pid);
    this.setData({xq:res,ids:e.currentTarget.dataset.id });
     }
       this.setData({
        showxq: true
       })
     
  },
// 选择时间段
selectTimeSlot(e) {
  this.setData({
    selectedTimeSlot: e.currentTarget.dataset.time,
    'ticket.playtime': e.currentTarget.dataset.time
  });
},
  onClosePopup() {
    this.setData({ showxq: false });
  },
  comment(name){
   //名字打码规则
   if(!name) return '';
   const len = name.length
   if (len === 2) {
    return name[0] + '*' 
  } 
  else if (len === 3) {
    return name[0] + '*' + name[2]  
  }
  else if (len > 3) {
    return name[0] + '*'.repeat(len-2) + name.slice(-1) 
  }
  return name 
},
async onChangesty(event) {
  console.log(event.currentTarget.dataset.id)
  this.setData({
    'ticket.num':event.detail,
    'ticket.total':Math.floor(event.detail*this.data.ticket.price)
  })
},
  
    //点击地图的跳转
navigateToMap(){
  wx.navigateTo({
    url: '/pages/scenicmap/scenicmap?address='+this.data.product.address
  });
},
//吸顶
  onPageScroll(e) {
    this.setData({
      isFixed: e.scrollTop > 200, 
      back:e.scrollTop>200
    });
  },
  hui(){
    wx.pageScrollTo({ //回到顶部
      scrollTop: 0,
      duration: 300 
    });
  },
  getData (event) {
    // 可以通过事件对象.detail 获取子组件传递给父组件的数据
    this.setData({
      show: event.detail
    })
    // wx.setStorageSync('hide', false)
  },
cho(event){
  this.setData({
    num:event.currentTarget.dataset.num
  })
},  
calculateTimeStatus(currentChoose, playtime, timeSlots) {
  const now = new Date();
  const currentHour = now.getHours();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const date = now.getDate().toString().padStart(2, '0');
  const nowday = `${month}.${date}`; // 今天的日期（如 "08.18"）

  let isdisable = false;
  let targetSlot = timeSlots[0];

  // 只有选择今天时，才判断是否禁用上午
  if (nowday === currentChoose) {
    if (currentHour >= 12 && !this.isAfternoon(playtime)) {
      isdisable = true; // 禁用上午
      targetSlot = timeSlots[1]; // 默认选中下午
    } else {
      isdisable = false; // 不禁用
      targetSlot = timeSlots[0]; // 默认选中上午
    }
  } else {
    console.log("今天不用进来知道了吗")
    // 非今天，不禁用任何时段
    isdisable = false;
    targetSlot = timeSlots[0];
  }

  return { isdisable, targetSlot };
},
 onDisplay(e) {
  const source = e.currentTarget.dataset.source; // 获取触发来源
  this.setData({ 
    showCalendar: true, 
    yd: false, 
    calendarSource: source 
  })
  },
  onClose() {
    this.setData({ showCalendar: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(event) {

    const selectedDate = new Date(event.detail); // 获取 Date 对象
    console.log(selectedDate)
    const day=this.formatDate(event.detail); //得到8.01
      // 找到选中日期的索引
  const activeIndex = this.data.dateList.findIndex(item => item.day === day);
    const selectedWeekday = this.week(selectedDate); 
    const dateList = this.data.dateList.map(item => {
      return {
          ...item,
          isAcvite: item.day === day
      };
  });
    // 调用封装好的 calculateTimeStatus 方法计算时段状态
    const { isdisable, targetSlot } = this.calculateTimeStatus(
      day, // 当前选中的日期（MM.DD格式）
      this.data.playtime, // 开始时间
      this.data.timeSlots // 时段数组
    );
    this.getProductInfo(
      this.data.product.tproductId ? this.data.product.tproductId : this.data.product.productId,
      this.data.product.tproductId ? 1 : 0
    );
   this.setData({
    dateList,
    choose:day,
    seleweekday:selectedWeekday,
    showCalendar: false, // 确保关闭日历
    date: day,
    scrollIntoId: `date-${activeIndex}`,
    isdisable,
    selectedTimeSlot: targetSlot,
    'ticket.playtime': targetSlot,
    'ticket.num': 1,
    ...(this.data.calendarSource === 'popup1' && { yd: true }) // 条件添加字段
  });
  },  
  dianjidate(event){
    const seleday=event.currentTarget.dataset.day;
    console.log(this.data.product)
  
    this.getProductInfo(
      this.data.product.tproductId ? this.data.product.tproductId : this.data.product.productId,
      this.data.product.tproductId ? 1 : 0
    );
    const seleweekday=event.currentTarget.dataset.weekday;
     const dateList = this.data.dateList.map(item => {
      return {
          ...item,
          isAcvite: item.day === seleday
      };
  });
  
    this.setData({
      dateList,
      choose:seleday,
      seleweekday:seleweekday
    })
  },
  navorder(){
    const currentYear = new Date().getFullYear();
    let name=this.data.product.productName;
    if(name==null || name==undefined || name==''){
      console.log("a")
      name=this.data.product.name
    }else{
      console.log("b")
      name=this.data.product.productName
    }
    reqSelstatus(this.data.ticket.id,wx.getStorageSync('userInfo').userId).then(result=>{
      console.log("result:"+result)
      //如果等于1就代表有这个订单并且还没付钱
        if(result==0){
          return new Promise((resolve) => {
            wx.showToast({
              title: '您还有一笔订单未付款',
              icon:'error'
            })
          });
        }
      wx.reLaunch({
        url: '/pages/order/order?ticket=' + encodeURIComponent(JSON.stringify(this.data.ticket)) + "&choose=" + this.data.choose+"&bigname="+name+"&year="+currentYear
      });
      })
  
  },
  splitText: function(originalText) {
    const text = originalText;
    
    // 匹配中文：[\u4e00-\u9fa5] 是中文Unicode范围
    const chineseMatch = text.match(/[\u4e00-\u9fa5\d\+]+/g);
    // 匹配英文：[a-zA-Z]+ 是英文大小写字母范围
    const englishMatch = text.match(/[a-zA-Z]+/g);
    
    // 提取匹配到的文本，没有匹配到则为空字符串
    const chineseText = chineseMatch ? chineseMatch.join('') : '';
    const englishText = englishMatch ? englishMatch.join('') : '';
    
    let jiabeforetext = '';
    let jiaaftertext = '';
    if (chineseText.includes('+')) {
        [jiabeforetext, jiaaftertext] = chineseText.split('+');
    } else {
        jiabeforetext = chineseText; // 如果没有加号，全部内容作为 before
    }

    // 更新数据
    this.setData({
      chineseText,
      englishText,
     jiabeforetext,  
     jiaaftertext 
    });
  },

  //查询商品数据方法一枚
  async getProductInfo(pid,type){
       
    if(type==0){
      //单品
      const p=await getProductById(pid)
      console.log(p.data.product)

      this.setData({
        product:p.data.product,
        'product.countnum':this.formatChineseNumber(p.data.product.countnum)
      })
    }else{
      //套餐
      const p=await getTProductById(pid)
      console.log(p.data.product)
     
      this.setData({
        product:p.data.product,
        address:false,
        'product.countnum':this.formatChineseNumber(p.data.product.countnum)
      })
    }
    const comment=await getProductComment(pid,type)
    const list=await getProductInfo(pid,type)
    let choosexg=this.data.choose.replace('.','-')
    reqGetInventory(pid,type,choosexg).then(res=>{
      console.log(res)
      this.setData({
        'yupiao':res.data.list.availableTickets
      })
    })
    this.setData({
      productInfo:list.data.productInfo,//商品信息
      commentList:comment.data.list
    })

    //数据处理
   
    for (let i = 0; i < this.data.productInfo.length; i++) {
      const element = this.data.productInfo[i];
      console.log(element);
      
      // 处理名称拆分
      this.splitText(element.pdName);
      element.chinesestr=this.data.chineseText,
      element.englishstr = this.data.englishText;
    }
    this.data.commentList.forEach(item=>{
      console.log(item)
      if(item.commentImg!=null && item.commentImg!=''){
      item.createAt=item.createAt.substring(0,10),
      item.plimg=item.commentImg.split(",")
      if(item.status==1){
        item.user.userName=this.comment(item.user.userName)
      }
    }
    })

    this.setData({ commentList: this.data.commentList,productInfo:this.data.productInfo});
  },

  formatChineseNumber(number) {
  
    if (number < 0) return '0';
    
    let result;
    if (number >= 100000000) {
      const yi = number / 100000000;
      result = (yi % 1 === 0 ? yi.toFixed(0) : yi.toFixed(1)) + '亿+';
    } else if (number >= 10000) {
      const wan = number / 10000;
      result = (wan % 1 === 0 ? wan.toFixed(0) : wan.toFixed(1)) + '万+';
    } else {
      result = number + '+';
    }
   
    return result;
  },
//用户
onusers(){
  const userInfo=wx.getStorageSync('userInfo');
  const token=wx.getStorageSync('token')
  if(token!=null){
    this.setData({
      user:userInfo,
      token
    })
  }
},
clearljt(e){
  let that=this;
  const ljt=e.currentTarget.dataset.ljt
  wx.showModal({
    title: '提示',
    content: '是否删除评论',
    success:function(res){
      if (res.confirm) {
        reqClearljt(ljt).then((res) => {  // 改用箭头函数
          wx.showToast({ title: '删除成功' });
          that.getProductInfo(that.data.commentList[0].productId, that.data.commentList[0].productType);
        }).catch((err) => {  // 这里也可以用箭头函数
          wx.showToast({ title: '删除失败', icon: 'error' });
        });
      }
    }
  })

},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    Promise.all([
      this.onusers(),
      this.riqi(),
      this.reqTimesss(options.id),
      this.getProductInfo(options.id,options.type)
      
    ])

    // const hi = wx.getStorageSync('hide') !== '' ? wx.getStorageSync('hide') : true;
    // console.log(hi)
    // this.setData({
    //   show:hi
    // })
  },

  
  async reqTimesss(a) {
    try {
      const response = await reqTimesss(a); // 替换yourApiFunction为
      const minTime = response['MIN(playtime)']; 
      const maxTime = response['MAX(endplaytime)']; 
      
      // 处理方法1：使用字符串操作
      const zhi = minTime.split(':').slice(0, 2).join(':') + '-' + 
                   maxTime.split(':').slice(0, 2).join(':');
      console.log()
      this.setData({
       timeabc:zhi
      });
      
      return response; // 返回结果供Promise.all使用
    } catch (error) {
      console.error('请求失败:', error);
      throw error; // 抛出错误以便Promise.all捕获
    }
  },
  riqi(){
    
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 归零时间
    const dateList = [];
    //生成15天
    for(let i=0;i<15;i++){
      const date=new Date();
      date.setDate(today.getDate()+i);//递增日期

    dateList.push({
      weekday:this.week(date),
      day:this.formatDate(date),
      isAcvite: i === 0, 
    })
  }
    this.setData({
      dateList,
      scrollIntoId: 'date-0' ,
      choose: dateList[0].day,
      seleweekday:dateList[0].weekday,
      'comment.name':this.comment(this.data.comment.name)
    })
    console.log(this.data.choose)
  },
  week(date){
    const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    return weekdays[date.getDay()];
  },
   // 格式化日期为 "MM.DD"
   formatDate(date) {
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}.${day}`;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
 
})